package com.wd.cloud.applet.common;

import com.wd.cloud.applet.common.enums.ResponseCodeEnum;
import java.io.Serializable;
import org.springframework.http.ResponseEntity;

/**
 * Description:
 *
 * @author <a href="mailto: 987707681@qq.com">hjx</a>
 * @version 1.0
 */
public class Response<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private String message = "操作失败";
    /**
     * 客户端错误
     */
    private Integer code = 104;
    private T data;

    public String getMessage() {
        return message;
    }

    public Response<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public Integer getCode() {
        return code;
    }

    public Response<T> setCode(Integer code) {
        this.code = code;
        return this;
    }

    public T getData() {
        return data;
    }

    public Response<T> setData(T data) {
        this.data = data;
        return this;
    }

    public static <T> Response<T> ok(T data) {
        return new Response<T>().setCode(0).setMessage("操作成功").setData(data);
    }


    public static Response ok() {
        return new Response().setCode(0).setMessage("操作成功");
    }

    public static Response error(Integer code, String msg) {
        return new Response().setCode(code).setMessage(msg);
    }

    /**
     * 现在采取的模式是统一返回200成功状态，这里做一个快捷方法
     * 控制层不直接返回Response对象，而是封装ResponseEntity，是因为ResponseEntity可以设置http相关很多配置
     * 比如状态码，header等，暂时没用而已
     *
     * @return 构建对象
     */
    public ResponseEntity<Response<T>> buildResponseEntity() {
        return ResponseEntity.ok(this);
    }

    public static <T> ResponseEntity<Response<T>> okToRe(T data) {
        return ok(data).buildResponseEntity();
    }

    public static Response error(ResponseCodeEnum codeEnum) {
        return new Response().setCode(codeEnum.getCode()).setMessage(codeEnum.getMsg());
    }
    public static ResponseEntity okToRe() {
        return ok().buildResponseEntity();
    }

    public static ResponseEntity errorToRe(Integer code, String msg) {
        return error(code, msg).buildResponseEntity();
    }

    @Override
    public String toString() {
        return "Response{" +
                "message='" + message + '\'' +
                ", code=" + code +
                ", data=" + data +
                '}';
    }
}
